#coding:utf-8
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth,messages
from django.db import transaction
from models import *
from forms import *
from django.utils.html import escape
from django.template.context import RequestContext


@never_cache
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        next = request.POST.get('next')
        if next == "None":next = "/index/"
        if form.is_valid():
            cd = form.cleaned_data
            user = auth.authenticate(username=cd['username'],password=cd['password'])
            if user:
                auth.login(request, user)
                return HttpResponseRedirect(next)
            else:
                alert = u"错误的用户名和密码"
                return render_to_response('login.html',locals())  
    else:
        next = request.GET.get('next')
        form = LoginForm()
    return render_to_response('login.html', locals())


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/index/")

@never_cache
@transaction.commit_on_success
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            if request.session.get('vcode') !=cd['vcode']:
                messages.error(request,u"验证码错误 ")
                return render_to_response('register.html',locals(),context_instance=RequestContext(request))
            
            users = User.objects.filter(username=cd['username'])
            if users.count()>0:
                messages.error(request,u"用户名已经存在 ")
                return render_to_response('register.html',locals(),context_instance=RequestContext(request))
            emails = User.objects.filter(email=cd['email'])
            if emails.count()>0:
                messages.error(request,u"电子邮箱已被使用 ")
                return render_to_response('register.html',locals(),context_instance=RequestContext(request))
            
            user = User()
            user.username = escape(cd['username'])
            user.set_password(cd['password'])
            user.email = cd['email']
            user.is_active = True
            user.save()
            city = City.objects.get(code="0")
            profile = UserProfile()
            profile.user = user
            profile.city = city
            profile.save()
            
            authuser = auth.authenticate(username=cd['username'],password=cd['password'])
            auth.login(request, authuser)
            return HttpResponseRedirect("/index/")
    else:
        form = RegisterForm()
    return render_to_response('register.html',locals())

def set_account(request):
    return HttpResponse("Hello index")

def reset_passwd(request):
    return HttpResponse("Hello index")



def vcode_image(request):
    import Image, ImageDraw, ImageFont, md5, datetime,cStringIO,random
    data = cStringIO.StringIO()
    draw = None
    cdata = None
    ctext = None
    try:
        bgcolor = (218,243,203) 
        fontcolor = (32,74,12) 
        im = Image.new("RGB",(160,48),bgcolor) 
        font = ImageFont.truetype("vcode.ttf", 30) 
        #font = ImageFont.truetype("/usr/share/fonts/chinese/TrueType/ukai.ttf", 24)     
        #font = ImageFont.load_default()
        #print dir(font)
        draw = ImageDraw.Draw(im)   
        mp = md5.new()   
        mp_src = mp.update(str(datetime.datetime.now()))   
        mp_src = mp.hexdigest()   
        ctext = mp_src[0:6]       
        draw.text((12,8), ctext,font=font,fill=fontcolor)   
        #画随机线
        linecolor= (0,0,0)   
        for i in range(0,3): 
            x1 = random.randint(0,100)   
            x2 = random.randint(0,100)   
            y1 = random.randint(0,77)   
            y2 = random.randint(0,88)   
            draw.line([(x1, y1), (x2, y2)], linecolor)   
        im.save(data,"PNG") 
        cdata = data.getvalue()
    except Exception,e:
        import traceback
        print e
        traceback.print_exc()
    finally:
        del draw   
        if data:data.close()
    #return cdata,ctext   
    request.session["vcode"] = ctext
    return HttpResponse(cdata, mimetype="image/png")








